package com.itheima.Controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.pojo.AddressBook;
import com.itheima.pojo.OrderDetail;
import com.itheima.pojo.Orders;
import com.itheima.pojo.ShoppingCart;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * reggie-com.itheima.Controller
 * Administrator
 * 2023-03-14
 * 15:44
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R addOrder(@RequestBody Orders orders){
        Long userId = BaseContext.getCurrentId();
        Long addressBookId = orders.getAddressBookId();
        //自动生成订单id
        Long orderId = IdWorker.getId();
        orders.setId(orderId);
        //设置订单号
        orders.setNumber(orderId.toString());
        //设置orders数据 设置用户id
        orders.setUserId(userId);
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getId,addressBookId);
        AddressBook addressbook = addressBookService.getOne(lqw);
        //设置consignee
        String consignee = addressbook.getConsignee();
        orders.setConsignee(consignee);
        //设置phone
        String phone = addressbook.getPhone();
        orders.setPhone(phone);
        //设置address
        String address = addressbook.getDetail();
        orders.setAddress(address);
        //设置amount  同时设置orderDetail
        LambdaQueryWrapper<ShoppingCart> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(lqw1);
        BigDecimal amount = new BigDecimal(0);
        for (ShoppingCart shoppingCart : list) {
            Integer number = shoppingCart.getNumber();
            BigDecimal amount1 = shoppingCart.getAmount();
            BigDecimal bigDecimal = BigDecimal.valueOf(number);
            BigDecimal multiply = amount1.multiply(bigDecimal);
            amount= amount.add(multiply);
            //设置orderDetail
            OrderDetail orderDetail = new OrderDetail();
            String name = shoppingCart.getName();
            //设置name
            orderDetail.setName(name);
            orderDetail.setOrderId(orderId);
            Long dishId = shoppingCart.getDishId();
            if (dishId!=null){
                //设置dishFlavor
                orderDetail.setDishId(dishId);
                String dishFlavor = shoppingCart.getDishFlavor();
                orderDetail.setDishFlavor(dishFlavor);
            }else {
                //设置setmealId
                Long setmealId = shoppingCart.getSetmealId();
                orderDetail.setSetmealId(setmealId);
            }
            //设置图片
            String image = shoppingCart.getImage();
            orderDetail.setImage(image);
            //设置数量
            orderDetail.setNumber(number);
            //设置价格
            orderDetail.setAmount(amount1);
            //添加如数据库
            orderDetailService.save(orderDetail);
        }
        orders.setAmount(amount);
        System.out.println("显眼一点哦空空空空3"+amount);
        //1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);
        //
        orders.setCheckoutTime(LocalDateTime.now());
        //
        orders.setOrderTime(LocalDateTime.now());
        //下单成功 删除购物车
        boolean save = ordersService.save(orders);
        if (save){
            LambdaQueryWrapper<ShoppingCart> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(ShoppingCart::getUserId,userId);
            shoppingCartService.remove(lqw2);
        }
        return R.success("清除购物车成功");
    }

    @GetMapping("/page")
    public  R selectPage(Integer page,Integer pageSize,Long number,LocalDateTime beginTime,LocalDateTime endTime){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        if (number!=null){
            lqw.eq(number!=null,Orders::getNumber,number);
        }else {
            lqw.between(beginTime!=null&&endTime!=null,Orders::getCheckoutTime,beginTime,endTime);
        }
        Page<Orders> page1 = ordersService.page(ordersPage,lqw);
        return  R.success(page1);
    }

    @GetMapping("/export")
    public void exportExcel(String beginTime, String endTime, HttpServletResponse response) throws IOException {
        ///**
        // * 文件下载（失败了会返回一个有部分数据的Excel）
        // * <p>
        // * 1. 创建excel对应的实体对象 参照{@link DownloadData}
        // * <p>
        // * 2. 设置返回的 参数
        // * <p>
        // * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
        // */
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //动态sql
        lqw.between(StringUtils.isNotEmpty(beginTime)&&StringUtils.isNotEmpty(endTime),Orders::getOrderTime,beginTime,endTime);
        List<Orders> list = ordersService.list(lqw);

        String fileName = UUID.randomUUID().toString();
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            //EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());
        //DownloadData.class 就是个对象 导出的数据是上面对象类型
            EasyExcel.write(response.getOutputStream(), Orders.class).sheet("模板").doWrite(list);
    }


}
